// 获取像素比 高清cavas
function getPixelRatio(context) {

    var backingStore = context.backingStorePixelRatio ||

        context.webkitBackingStorePixelRatio ||

        context.mozBackingStorePixelRatio ||

        context.msBackingStorePixelRatio ||

        context.oBackingStorePixelRatio ||

        context.backingStorePixelRatio || 1;

    return (window.devicePixelRatio || 1) / backingStore;

};
var wheel = new Wheel();

// 公共类
function Wheel() {
    let cav = document.getElementById('canvas');
    this.pointerRange = [];
    this.pointerIndex = 0;
    this.turned = []; //已经转中的下标数组
    this.turnTargetRotate = []; //要转的目的数组
    this.turnedCount = 0; // 转盘次数
    this.startTurn = false; // 开始抽
    this.delay = 20;
    this.speed = 1; //转速
    this.ctx = cav.getContext('2d');
    this.ratio = getPixelRatio(this.ctx);
    this.w = window.innerWidth > 750 ? 750 : window.innerWidth;
    this.h = window.innerWidth > 750 ? 1624 : 812;
    cav.style.width = this.w + 'px';
    cav.style.height = this.h + 'px';
    cav.width = this.w * this.ratio;
    cav.height = this.h * this.ratio;
}
Wheel.prototype.updatePointerIndex = function (rotate) {
    let rotateV = rotate % 360;
    let index = this.pointerRange.findIndex(d => rotateV < d);
    this.pointerIndex = index == -1 ? 0 : index;
}

// 转盘类
function AwardRound({
    cx,
    cy,
    cr = 100,
    data = []
}) {
    let angleStore = 0;
    let sum = 0;
    this.cx = cx * wheel.ratio;
    this.cy = cy * wheel.ratio;
    this.cr = cr * wheel.ratio;
    this.count = data.length;
    this.data = data.map((d, i) => {
        sum += d.angle;
        let prevData = data[i - 1];
        angleStore += d.angle + (i - 1 > 0 ? prevData.angle : 0);
        let startAngle = - 90 - (d.angle / 2);
        d.beginAngle = startAngle / 180 * Math.PI;
        d.endAngle = (startAngle + d.angle) / 180 * Math.PI;
        if (i == 0) {
            d.rotateAngle = 0;

        } else {
            d.rotateAngle = angleStore;
        }
        wheel.pointerRange.push(sum - (data[0].angle / 2));
        if (d.isTurn) {
            let prevItem = wheel.pointerRange[i - 1];
            let baseRotate = (wheel.pointerRange[i] - prevItem) / 2 + prevItem;
            wheel.turnTargetRotate.push({
                rotate: baseRotate + (baseRotate > 270 ? 0 : 360),
                index: i
            })
        }

        return d;
    });
}
AwardRound.prototype.render = function () {
    let iconW;
    this.data.forEach((d, i) => {
        iconW = (d.imgWidth || 30) * wheel.ratio;
        wheel.ctx.save();
        wheel.ctx.translate(this.cx, this.cy);
        wheel.ctx.rotate((d.rotateAngle) * Math.PI / 360);
        wheel.ctx.beginPath();

        // 画底盘
        wheel.ctx.fillStyle = d.background || '#fdf1e7';
        wheel.ctx.arc(0, 0, this.cr, d.beginAngle, d.endAngle);
        wheel.ctx.lineTo(0, 0);
        wheel.ctx.fill()
        // 名字
        wheel.ctx.fillStyle = d.color || '#000';
        wheel.ctx.font = `${d.fontSize ? d.fontSize * wheel.ratio : 16}px 微软雅黑`;
        wheel.ctx.textAlign = 'center';
        wheel.ctx.fillText(d.name || '', 0, - this.cr + 20 * wheel.ratio);

        // 图片
        if (d.icon) {
            wheel.ctx.drawImage(d.icon, -iconW / 2, -this.cr + 30 * wheel.ratio, iconW, iconW);
        }
        // 浮层
        wheel.ctx.fillStyle = '#000';
        wheel.ctx.globalAlpha = i == wheel.pointerIndex || wheel.turned.includes(i) ? 0 : 0.5;
        wheel.ctx.arc(0, 0, this.cr, d.beginAngle, d.endAngle);
        wheel.ctx.lineTo(0, 0);
        wheel.ctx.fill();

        wheel.ctx.restore();
    })

}

// 按钮类
function Button({
    cx,
    cy
}) {
    this.cx = cx * wheel.ratio;
    this.cy = cy * wheel.ratio;
    this.rotate = 0;
    this.awradResult = document.querySelectorAll('.award_result_item_icon');
}
Button.prototype.render = function () {
    let tmpW = 25 * wheel.ratio;
    wheel.ctx.save()
    wheel.ctx.translate(this.cx, this.cy);
    wheel.ctx.rotate(this.rotate * Math.PI / 180);
    wheel.ctx.beginPath()
    wheel.ctx.fillStyle = '#FF910B';
    wheel.ctx.arc(0, 0, 50 * wheel.ratio, 0, Math.PI * 2);
    wheel.ctx.fill();
    wheel.ctx.moveTo(0, 0);
    wheel.ctx.lineTo(tmpW, 0);
    wheel.ctx.lineTo(0, -80 * wheel.ratio);
    wheel.ctx.lineTo(-tmpW, 0);
    wheel.ctx.fill();
    wheel.ctx.restore();
}
Button.prototype.update = function () {
    this.rotate += wheel.speed;
    let diff = this.rotate - wheel.turnTargetRotate[wheel.turnedCount].rotate;
    if (wheel.startTurn) { // 开始转了
        if (diff >= 0) { // 达到阈值
            if (wheel.delay == 20) {
                // 第一次倒计时才执行中奖动画
                this.awradResult[wheel.turnedCount].style.cssText = 'transform: translateY(-50%)';
            }
            wheel.delay--; //延时器
            if (wheel.delay > 0) {
                // 休息一下
                this.rotate = wheel.turnTargetRotate[wheel.turnedCount].rotate; // 保持抽到位置
                wheel.speed = 0; //停止转动
            } else {
                // 转下一次
                wheel.turnedCount++; // 中次+1
                wheel.turned.push(wheel.turnTargetRotate[wheel.turnedCount - 1].index);
                wheel.speed = wheel.turnedCount == 2 ? 10 : 20;
                wheel.delay = 20;
                if (wheel.turnedCount < 3) {
                    this.rotate = 0;
                }
            }
        } else if (diff >= -90 && wheel.turnedCount == 2) {
            wheel.speed = 1;
        }
    }
    wheel.updatePointerIndex(this.rotate);
}

// 背景类
function Background({ bg, cx, cy, width, height }) {
    this.bgImg = bg;
    this.cx = cx * wheel.ratio;
    this.cy = cy * wheel.ratio;
    this.width = width * wheel.ratio;
    this.height = height * wheel.ratio;
}
Background.prototype.render = function () {
    wheel.ctx.drawImage(this.bgImg, this.cx, this.cy, this.width, this.height)
}


function myAlert({
    content,
    delay = 1000
}) {
    let div = document.createElement('div');
    div.innerHTML = content;
    div.style.cssText = `
        position:absolute;
        top:50%;
        left: 50%;
        z-index:9999; 
        transform: translate(-50%,-50%);
        background: rgba(0,0,0,0.6);
        color: #fff;
        font-size:13px;
        border-radius: 3px;
        line-height:1.8;
        padding:0 10px;
    `;
    document.body.appendChild(div);
    setTimeout(() => {
        document.body.removeChild(div);
    }, delay)
}


// 资源、数据加载
var bgImg = new Image();
bgImg.src = 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/promotion/bg.png';
var awardData = [
    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/thanks.png',
        name: '感谢参与',
        background: '#fdf1e7',
        color: '#C24603',
        fontSize: '13',
        angle: 45,
        imgWidth: 36,
    },
    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/award_3.png',
        name: 'AirJordan1',
        background: '#FFB876',
        color: '#C24603',
        fontSize: '11',
        angle: 25,
        imgWidth: 30,
    },
    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/award_1.png',
        name: 'iPhone手机',
        background: '#BD1600',
        color: '#FEE28A',
        fontSize: '11',
        angle: 25,
        imgWidth: 30,
        isTurn: true,
    },
    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/award_2.png',
        name: '蓝牙音箱',
        background: '#FFDAB2',
        color: '#C24603',
        fontSize: '11',
        angle: 25,
        imgWidth: 30,
    },

    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/thanks.png',
        name: '感谢参与',
        background: '#fdf1e7',
        color: '#C24603',
        fontSize: '13',
        angle: 45,
        imgWidth: 36,
    },
    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/award_3.png',
        name: 'AirJordan1',
        background: '#FFB876',
        color: '#C24603',
        fontSize: '11',
        angle: 25,
        imgWidth: 30,
    },
    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/award_1.png',
        name: 'iPhone手机',
        background: '#BD1600',
        color: '#FEE28A',
        fontSize: '11',
        angle: 25,
        imgWidth: 30,
        isTurn: true,
    },
    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/award_2.png',
        name: '蓝牙音箱',
        background: '#FFDAB2',
        color: '#C24603',
        fontSize: '11',
        angle: 25,
        imgWidth: 30,
    },

    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/thanks.png',
        name: '感谢参与',
        background: '#fdf1e7',
        color: '#C24603',
        fontSize: '13',
        angle: 45,
        imgWidth: 36,
    },
    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/award_3.png',
        name: 'AirJordan1',
        background: '#FFB876',
        color: '#C24603',
        fontSize: '11',
        angle: 25,
        imgWidth: 30,
    },
    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/award_1.png',
        name: 'iPhone手机',
        background: '#BD1600',
        color: '#FEE28A',
        fontSize: '11',
        angle: 25,
        imgWidth: 30,
        isTurn: true,
    },
    {
        icon: 'https://mdhw.oss-cn-hangzhou.aliyuncs.com/icon/award_2.png',
        name: '蓝牙音箱',
        background: '#FFDAB2',
        color: '#C24603',
        fontSize: '11',
        angle: 25,
        imgWidth: 30,
    },
];
awardData = awardData.map(d => {
    if (d.icon) {
        let img = new Image();
        img.src = d.icon;
        d.icon = img
    }
    return d
})


window.onload = function () {
    document.querySelector('.loading').remove();
    const btnDom = document.querySelector('.button');
    const cavInnerDom = document.querySelector('.canvas-wrapper-inner');
    const dialogDom = document.querySelector('.dialog');
    const dialogCloseDom = document.querySelector('.dialog-close');
    const inputDom = document.querySelector('#phoneInput');
    const openAwardDom = document.querySelector('.open_award');
    let bgCx = 10;
    let iconW = wheel.w - bgCx * 2;
    let iconH = iconW * (846 / 720);
    let bgCy = (wheel.h - iconW) / 2 + 90;
    let cx = wheel.w / 2;
    let cr = cx - 35;
    let cy = bgCy + cr + 25;

    btnDom.style.top = (cy - 50) + 'px';
    cavInnerDom.style.bottom = wheel.h / 2 - 30 + 'px';
    const background = new Background({
        bg: bgImg,
        cx: bgCx,
        cy: bgCy,
        width: iconW,
        height: iconH
    });
    const awardRound = new AwardRound({
        cx: cx,
        cy: cy,
        cr: cr,
        data: awardData
    });
    const button = new Button({
        cx,
        cy,
    });
    const clickDown = function () {
        if (wheel.startTurn) {
            if (wheel.turnedCount == 3) {
                // 查看奖品
                dialogDom.classList.remove('hide');
            }
            return;
        }
        // 开始转动
        btnDom.classList.remove('scaleAni')
        button.rotate = 0;
        wheel.startTurn = true;
        wheel.speed = 20;
    }
    dialogCloseDom.addEventListener('click', function () {
        dialogDom.classList.add('hide')
    })
    btnDom.addEventListener('click', clickDown)
    openAwardDom.addEventListener('click', function () {
        // 开奖
        let reg = /^1[3456789]\d{9}$/;
        let phone = inputDom.value;
        if (!phone) {
            return;
        }
        if (reg.test(phone)) {
            window.location.href = 'https://wwww.baidu.com?phone=' + btoa(phone);
        } else {
            myAlert({
                content: '手机号码格式不正确'
            })
        }

    })

    function doAnimate() {
        // 清除画布
        wheel.ctx.clearRect(0, 0, 10000, 10000)
        // 渲染转盘背景
        background.render();
        // 渲染转盘
        awardRound.render();
        // 渲染按钮
        button.update();
        button.render();
        if (wheel.turnedCount < 3) {
            setTimeout(() => {
                doAnimate();
            }, 16.6)
        } else {
            dialogDom.classList.remove('hide');
            btnDom.classList.add('button_after');
        }
    }
    doAnimate();

}